<?php


namespace app\admin\controller\admin;


use app\admin\annotation\UseAuth;
use app\admin\controller\BaseController;
use app\admin\validate\AdminRoleValidate;
use app\common\http\exception\AppException;
use app\common\library\FormDataValidate;
use ke\auth\model\KeRole;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\DbException;
use think\Response;
use think\response\Json;

/**
 * Class RoleController
 * @package app\admin\controller\admin
 * @UseAuth(policy="Acl")
 */
class RoleController extends BaseController
{

    /**
     * 角色列表
     * @return mixed
     * @throws DbException
     * @route('admin/roles', 'get')
     */
    public function index()
    {
        $result = KeRole::where(function (Query $query) {
            $key = $this->request->get('key');
            if ($key) {
                $query->whereLike('name', "%{$key}%");
            }
        })
            ->order('sort', 'asc')
            ->order('create_time', 'desc')
            ->paginate();

        return $result->render();
    }


    /**
     * 角色详情
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @route('admin/role/:id', 'get')
     */
    public function read($id)
    {
        $result = KeRole::where('id', $id)->findOrFail();

        return $this->success($result);
    }


    /**
     * 添加 / 编辑角色
     * @param string $action
     * @return Response|Json
     * @throws AppException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/role/:action', 'post')
     */
    public function post($action)
    {
        $form = new FormDataValidate(AdminRoleValidate::class, $action);

        if ($form->id) {
            $data = KeRole::where('id', $form->id)->find();
            if (!$data) {
                throw new AppException('记录不存在');
            }
        } else {
            $data = new KeRole();
        }
        $data->save($form->toArray());

        $this->recordActionLog(sprintf('%s角色：%s', $action == 'add' ? '添加' : '编辑', $data->name));

        return $this->success($data);
    }


    /**
     * 角色删除
     * @return Response|Json
     * @throws AppException
     * @route('admin/role', 'delete')
     */
    public function delete()
    {
        $id = $this->request->post('id/a', [], 'intval');
        if (empty($id)) {
            throw new AppException('没有删除的项目');
        }
        Db::transaction(function () use($id) {
            $list = KeRole::where('id', 'in', $id)->field('id,name')->select();
            foreach ($list as $item) {
                $this->recordActionLog(sprintf('删除角色：%s', $item->name));
                $item->delete();
            }
        });

        return $this->success();
    }


    /**
     * 策略列表
     * @param $id
     * @return Response|Json
     * @throws AppException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/role/:id/policys', 'get')
     */
    public function getPolicy($id)
    {
        $role = KeRole::where('id', $id)->find();
        if (!$role) {
            throw new AppException('角色不存在');
        }
        $list = $role->permissions();

        return $this->success([
            'list'=>$list
        ]);
    }


    /**
     * 设置角色策略
     * @param $id
     * @return Response|Json
     * @throws AppException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/role/:id/set_policy', 'post')
     */
    public function setPolicy($id)
    {
        $user = KeRole::where('id', $id)->find();
        if (!$user) {
            throw new AppException('角色不存在');
        }
        $data = $this->request->post('policys/a', [], 'intval');

        Db::transaction(function () use($user, $data) {
            $user->clearPermission();
            foreach ($data as $v) {
                $user->addPermission($v);
            }
            $this->recordActionLog(sprintf('设置角色：%s的策略', $user->name));

        });

        return $this->success();
    }

}
